package com.jianganming.serial;

import java.io.*;

public class JavaSerializer implements ISerializer {
    @Override
    public <T> byte[] serialize(T obj) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream outputStream=null;
        try {
            outputStream = new ObjectOutputStream(out);
            outputStream.writeObject(obj);
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
                if (outputStream != null) {
                    outputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        ObjectInputStream inputStream=null;
        try {
            inputStream = new ObjectInputStream(in);
            Object o = inputStream.readObject();
            return (T)o;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
                if (inputStream != null) {
                    inputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return null;
    }
}
